const MongoClient = require('mongodb').MongoClient;
const config = require('config');
const url = 'mongodb://' + config.dbConfig.mongodb.host + ':' + config.dbConfig.mongodb.port;
const dbName = config.dbConfig.mongodb.dbName;
var mClient;

function initDB(callback) {
    if (!mClient || !mClient.isConnected()) {
        MongoClient.connect(url, {
            useNewUrlParser: true
        }, function(err, client) {
            console.log("Connected successfully to mongodb server");
            mClient = client;
            var db = mClient.db(dbName);
            callback(db);
        });
    } else {
        var db = mClient.db(dbName);
        callback(db);
    }
}

exports.find = (collectionName, value, callback) => {
    initDB((db) => {
        const collection = db.collection(collectionName); //'messages'
        collection.find(value).toArray((err, result) => {
            if (err) {
                console.error('find: ' + collectionName + ' value:' + JSON.stringify(value));
                console.error(err);
            }
            callback(result);
        });
    });
}

exports.insertOne = (collectionName, value, callback) => {
    initDB((db) => {
        const collection = db.collection(collectionName);
        collection.insertOne(value, (err, result) => {
            if (err) {
                console.error('insertOne: ' + collectionName + ' value:' + JSON.stringify(value));
                console.error(err);
            }
            callback(result);
        });
    });
}

exports.insertMany = (collectionName, values, callback) => {
    initDB((db) => {
        const collection = db.collection(collectionName);
        collection.insertMany(values, (err, result) => {
            if (err) {
                console.error('insertMany: ' + collectionName + ' values:' + JSON.stringify(values));
                console.error(err);
            }
            callback(result);
        });
    });
}

exports.updateOne = (collectionName, filter, update, callback) => {
    initDB((db) => {
        const collection = db.collection(collectionName);
        collection.updateOne(filter, update, function(err, result) {
            if (err) {
                console.error('updateOne: ' + collectionName + ' filter:' + JSON.stringify(filter) + ' update:' + (update));
                console.error(err);
            }
            callback(result);
        });
    });
}

exports.updateMany = (collectionName, filter, update, callback) => {
    initDB((db) => {
        const collection = db.collection(collectionName);
        collection.updateMany(filter, update, function(err, result) {
            if (err) {
                console.error('updateMany: ' + collectionName + ' filter:' + JSON.stringify(filter) + ' update:' + JSON.stringify(update));
                console.error(err);
            }
            callback(result);
        });
    });
}